package com.ben.multiple.mail;

import java.util.Arrays;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * @author BenJin Yin
 * @date 2020/7/9
 */
@Component
@Slf4j
public class SendMailService {
    private final MailProperties mailProperties;
    private final JavaMailSender javaMailSender;

    public SendMailService(MailProperties mailProperties, JavaMailSender javaMailSender) {
        this.mailProperties = mailProperties;
        this.javaMailSender = javaMailSender;
    }

    public Boolean send(String to, String subject, String text) {
        if (StringUtils.isEmpty(to) || StringUtils.isEmpty(subject) || StringUtils.isEmpty(text)) {
            log.error("参数不能为空");
            return false;
        }
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(mailProperties.getUsername());
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(text);
        javaMailSender.send(mailMessage);
        log.info("发送邮件：{}", mailMessage);
        return true;
    }

    public Boolean batchSend(Set<String> toSet, String subject, String text) {
        if (CollectionUtils.isEmpty(toSet) || StringUtils.isEmpty(subject) || StringUtils.isEmpty(text)) {
            log.error("参数不能为空");
            return false;
        }
        SimpleMailMessage[] mailMessages = toSet.stream().map(to -> {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(mailProperties.getUsername());
            mailMessage.setTo(to);
            mailMessage.setSubject(subject);
            mailMessage.setText(text);
            return mailMessage;
        }).toArray(SimpleMailMessage[]::new);
        javaMailSender.send(mailMessages);
        log.info("批量发送邮件：{}", Arrays.asList(mailMessages));
        return true;
    }
}
